<template>
	<!-- 	<page-meta>
		<navigation-bar :title="nbTitle" olor="nbFrontColor" :loading="nbLoading" :front-color="nbFrontColor"
			:background-color="nbBackgroundColor" />
	</page-meta> -->
	<view class="">
		<scroll-view class="conversations" scroll-y="true">
			<view v-if="conversations.length > 0">
				<view class="scroll-item" v-for="(conversation, key) in conversations" :key="key">
					<view class="item-head">
						<image src="/static/images/chatroom/school.png" class="head-icon"></image>
						<view class="item-head_unread" v-if="conversation.unread">{{ conversation.unread }}</view>
					</view>
					<view class="scroll-item_info" @click="chat(conversation)">
						<view class="item-info-top">
							<text class="item-info-top_name">{{ conversation.data.name }}</text>
							<view class="item-info-top_time">{{ formatDates(conversation.lastMessage.timestamp) }}
							</view>
						</view>
						<view class="item-info-bottom">
							<view class="item-info-bottom-item">
								<view class="item-info-top_content" v-if="!conversation.lastMessage.recalled">
									<text class="unread-text">
										{{ conversation.lastMessage.read === false && conversation.lastMessage.senderId === id ? '[未读]' : '' }}
									</text>

									<text v-if="conversation.lastMessage.senderId ===id">我: </text>
									<text
										v-else>{{ conversation.type === 'group' ? conversation.lastMessage.senderData.name : conversation.data.name }}:
									</text>
									<text
										v-if="conversation.lastMessage.type === 'text'">{{ conversation.lastMessage.payload.text }}</text>
									<text v-else-if="conversation.lastMessage.type === 'video'">[视频消息]</text>
									<text v-else-if="conversation.lastMessage.type === 'audio'">[语音消息]</text>
									<text v-else-if="conversation.lastMessage.type === 'image'">[图片消息]</text>
									<text v-else-if="conversation.lastMessage.type === 'file'">[文件消息]</text>
									<text v-else-if="conversation.lastMessage.type === 'order'">[自定义消息:订单]</text>
									<text v-else>[[未识别内容]]</text>
								</view>
								<view class="item-info-top_content" v-else>

									<text v-if="conversation.lastMessage.senderId ===id">
										你撤回了一条消息
									</text>
									<text v-else>
										{{ conversation.type === 'group' ? conversation.lastMessage.senderData.name : conversation.data.name }}
										撤回了一条消息
									</text>
								</view>
								<view class="item-info-bottom_action" @click.stop="showAction(conversation)"></view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- <view class="no-conversation" v-else>当前没有会话</view> -->
			<view class="action-container" v-if="actionPopup.visible" :class="lll?'':'tmp'">
				<view class="layer" @click="actionPopup.visible = false"></view>
				<view class="action-box">
					<view class="action-item" @click="topConversation">
						{{ actionPopup.conversation.top ? '取消置顶' : '置顶聊天' }}
					</view>
					<view class="action-item" @click="deleteConversation" :style="lll?'tmp':''">删除聊天</view>
				</view>
			</view>
		</scroll-view>
		<view class="content">

			<mark-slide-list :list="list" :button="buttonList" :border="true" @click="clickMethod"
				@change="changeMethod">
			</mark-slide-list>
		</view>
		<view class="" v-if="conversations.length==0&&list.length==0">
			<u-empty margin-top="100" text="暂无消息" mode="favor"></u-empty>
		</view>
	</view>

</template>

<script>
	import markSlideList from '../../components/mark-slide-list/mark-slide-list.vue'
	import {
		getMyMessage,
		deleteMyMessage,
		updateTopping
	} from "@/api/message/message.js"
	import {
		formatDate
	} from '@/api/time.js';
	import {
		profileClassS
	} from "@/api/system/user.js"
	import {
		formatDates
	} from "@/api/utils.js"
	// let goEasy = getApp().globalData.goEasy;
	export default {
		components: {
			markSlideList
		},
		name: 'slide-list',
		data() {
			return {
				lll: false,
				friends: [],
				groups: [],
				show: true,
				unreadTotal: 0,
				conversations: [],

				actionPopup: {
					conversation: null,
					visible: false
				},
				id: null,
				nbTitle: '消息',
				nbLoading: false,
				nbFrontColor: '#000000',
				nbBackgroundColor: '#fcc10d',
				list: [

				],
				buttonList: [{
						title: '置顶',
						background: '#4d93fe'
					}, {
						title: '取消置顶',
						background: '#4d93fe'
					},
					{
						title: '标为未读',
						background: '#ff9c01'
					},
					{
						title: '标为已读',
						background: '#ff9c01'
					},
					{
						title: '删除',
						background: '#fe5869'
					},
				]
			};
		},
		onShow() {
			this.getMyMessage()
			profileClassS().then((res) => {
				// this.groups = res.data
				console.log(res.data);
				if (res.data.length != 0) {
					this.id = res.data[0].userId
					this.connectGoEasy(res.data[0].userId); //连接goeasy
					this.subscribeGroup(); //建立连接后，就应该订阅群聊消息，避免漏掉

					this.goEasy.im.on(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this
						.renderConversations); //监听会话列表变化
					this.loadConversations(); //加载会话列表

				}

			})
		},
		beforeDestroy() {
			this.goEasy.im.off(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderConversations);
		},
		onHide() {
			this.getMyMessage()
		},
		//监听下拉刷新
		onPullDownRefresh() {
			this.refresh()

		},
		methods: {
			formatDates,
			// 连接goEasy
			connectGoEasy(data) {
				uni.showLoading();
				this.goEasy.connect({
					id: data,
					data: {
						name: this.$store.state.user.name,
						avatar: this.$store.state.user.avatar
					},
					onSuccess: () => {
						// console.log('GoEasy connect successfully.')
					},
					onFailed: (error) => {
						// console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error
						// 	.content);
					},
					onProgress: (attempts) => {
						// console.log('GoEasy is connecting', attempts);
					}
				});
			},
			subscribeGroup() {
				profileClassS().then((res) => {
					// console.log(res);
					let groups = res.data;
					let groupIds = groups.map(item => item.classId);
					this.goEasy.im.subscribeGroup({
						groupIds: groupIds,
						onSuccess: function() {
							// console.log('订阅群消息成功');
						},
						onFailed: function(error) {
							// console.log('订阅群消息失败:', error);
						}
					});
				})


			},
			// 加载最新的会话列表
			loadConversations() {
				this.goEasy.im.latestConversations({
					onSuccess: (result) => {
						uni.hideLoading();
						let content = result.content;
						this.renderConversations(content);
						let unreadTotal = content.unreadTotal;
						if (unreadTotal > 0) {
							uni.setTabBarBadge({
								index: 2,
								text: unreadTotal.toString()
							});
						} else {
							uni.removeTabBarBadge({
								index: 2
							});
						}
					},
					onFailed: (error) => {
						uni.hideLoading();
						console.log('获取最新会话列表失败, error:', error);
					}
				});
			},
			renderConversations(content) {
				this.conversations = content.conversations;
			},
			// connectGoEasy(data) {
			// 	let self = this;
			// 	let userData = {
			// 		avatar: this.$store.state.user.avatar,
			// 		nickname: this.$store.state.user.name
			// 	}
			// 	this.goEasy.connect({
			// 		id: data,
			// 		data: userData,
			// 		onSuccess: function() {
			// 			console.log("GoEasy connect successfully.")

			// 			// 加载在线用户列表
			// 			// self.loadOnlineUsers();
			// 		},
			// 		onFailed: function(error) {
			// 			console.log("Failed to connect GoEasy, code:" + error.code + ",error:" + error
			// 				.content);
			// 		},
			// 		onProgress: function(attempts) {
			// 			console.log("GoEasy is connecting", attempts);
			// 		}
			// 	});
			// },
			privateChat(friend) {
				uni.navigateTo({
					url: './privateChat?to=' + friend.id
				});
			},

			groupChat(group) {
				this.roomToken = {
					roomId: group.classId,
					roomName: group.typeName,
					userId: group.userId,
					nickname: this.$store.state.user.name,
					avatar: this.$store.state.user.avatar
				};
				let roomTokenAsJsonString = JSON.stringify(this.roomToken)
				console.log(roomTokenAsJsonString);
				uni.removeTabBarBadge({
					index: 2
				});
				uni.navigateTo({
					// 连接goEasy
					url: "./groupChat?to=" + roomTokenAsJsonString
				})


			},
			topConversation() { //会话置顶

				this.actionPopup.visible = false;
				let conversation = this.actionPopup.conversation;
				let description = conversation.top ? '取消置顶' : '置顶';
				this.goEasy.im.topConversation({
					conversation: conversation,
					top: !conversation.top,
					onSuccess: function() {
						uni.showToast({
							title: description + '成功',
							icon: 'none'
						});
					},
					onFailed: function(error) {
						console.log(description, '失败：', error);
					}
				});
			},
			deleteConversation() {
				this.lll = true
				uni.showModal({
					content: '确认删除这条会话吗？',
					success: (res) => {
						if (res.confirm) {
							this.lll = false
							let conversation = this.actionPopup.conversation;
							this.actionPopup.visible = false;
							this.goEasy.im.removeConversation({
								conversation: conversation,
								onSuccess: function() {

									console.log('删除会话成功');
								},
								onFailed: function(error) {
									console.log(error);
								},
							});
						} else {
							this.actionPopup.visible = false;
							this.lll = false
						}
					},
				})
			},
			showAction(conversation) {
				this.actionPopup.conversation = conversation;
				this.actionPopup.visible = true;
				this.show = true
			},
			chat(conversation) {
				this.roomToken = {
					roomId: conversation.groupId,
					roomName: conversation.data.name,
					userId: this.id,
					nickname: this.$store.state.user.name,
					avatar: this.$store.state.user.avatar
				};
				let roomTokenAsJsonString = JSON.stringify(this.roomToken)
				let path = conversation.type === this.GoEasy.IM_SCENE.PRIVATE ?
					'/pages/chatRoom/privateChat?to=' + conversation.userId :
					'/pages/chatRoom/groupChat?to=' + roomTokenAsJsonString;
				uni.removeTabBarBadge({
					index: 2
				});
				uni.navigateTo({
					url: path
				});
			},
			getMyMessage() {
				let that = this
				getMyMessage().then((res) => {
					this.list = res
					for (let i = 0; i < this.list.length; i++) {
						that.$set(this.list[i], "formatDate", formatDate(Date.parse(this.list[i].createTime)))

						that.$set(this.list[i], "id", i + 1)
						that.$set(this.list[i], "isShare", true)
						that.$set(this.list[i], "slide_x", 0)
						that.$set(this.list[i], "surname", this.list[i].remark.substring(0, 1))

						if (this.list[i].msgAvatar == null) {
							this.list[i].msgAvatar = "null"
						}

						if (this.list[i].topping == null) {
							this.list[i].topping = "null"
						}
					}
				})
			},
			changeMethod(data, button, index) {
				let self = this

				if (button.title === '删除') {
					uni.showModal({
						title: '',
						content: '确定要删除该信息吗？',
						confirmText: '删除',
						confirmColor: '#ff3b32',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定')
								deleteMyMessage(data.msgId).then((res) => {
									self.getMyMessage()
								})
								uni.showToast({
									icon: "success",
									title: '操作成功!',
									duration: 2000
								});
							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})
				} else if (button.title == '置顶') {
					updateTopping(data.msgId, 1).then((res) => {
						self.getMyMessage()
					})
				} else if (button.title == '取消置顶') {
					updateTopping(data.msgId, 2).then((res) => {
						self.getMyMessage()
					})
				} else if (button.title == '标为已读') {
					updateTopping(data.msgId, 3).then((res) => {
						self.getMyMessage()
					})
				} else if (button.title == '标为未读') {
					updateTopping(data.msgId, 4).then((res) => {
						self.getMyMessage()
					})
				}
			},
			clickMethod(data) {
				updateTopping(data.msgId, 3).then((res) => {
					uni.navigateTo({
						url: '/pages/message/message-detail/index?item=' + encodeURIComponent(JSON
							.stringify(
								data))
					})

				})
			}, //下拉刷新
			refresh() {
				setTimeout(() => {
					// 此处可写下拉更新消息逻辑
					this.getMyMessage()
					uni.stopPullDownRefresh();
				}, 1000)
				//停止下拉刷新
				setTimeout(() => {
					uni.showToast({
						title: '刷新成功',
						icon: 'none',
						duration: 1000
					})
				}, 1002)
			},
		}
	};
</script>

<style lang="scss" scoped>
	page {
		background: #f2f2f2;
	}

	.conversations {
		width: 750rpx;
		overflow-x: hidden;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		height: 100%;
	}

	.conversations .scroll-item {
		height: 152rpx;
		display: flex;
		align-items: center;
		padding-left: 32rpx;
	}

	.conversations .scroll-item .head-icon {
		width: 100rpx;
		height: 100rpx;
		margin-right: 28rpx;
	}

	.conversations .scroll-item_info {
		height: 151rpx;
		width: 590rpx;
		padding-right: 32rpx;
		box-sizing: border-box;
		border-bottom: 1px solid #EFEFEF;
	}

	.conversations .scroll-item_info .item-info-top {
		padding-top: 20rpx;
		height: 60rpx;
		line-height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

	}

	.conversations .item-info-top_name {
		font-size: 34rpx;
		color: #262628;
	}

	.conversations .item-info-top_time {
		font-size: 26rpx;
		color: rgba(179, 179, 179, 0.8);
		font-family: Source Han Sans CN;
	}

	.conversations .item-info-bottom {
		height: 40rpx;
		line-height: 40rpx;
		overflow: hidden;
	}

	.conversations .item-info-bottom-item {
		display: flex;
		justify-content: space-between;
	}

	.item-info-bottom .item-info-top_content {
		font-size: 30rpx;
		color: #b3b3b3;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;

	}

	.item-info-bottom .item-info-bottom_action {
		width: 50rpx;
		height: 50rpx;
		font-size: 20rpx;
		background: url("@/static/images/action.png") no-repeat center;
		background-size: 28rpx 30rpx;
	}

	.no-conversation {
		width: 100%;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		color: #9D9D9D;
	}

	.item-head {
		position: relative;
	}

	.item-head .item-head_unread {
		padding: 6rpx;
		background-color: #EE593C;
		color: #FFFFFF;
		font-size: 24rpx;
		line-height: 28rpx;
		border-radius: 24rpx;
		min-width: 24rpx;
		min-height: 24rpx;
		text-align: center;
		position: absolute;
		top: 0;
		right: 15rpx;
	}

	.action-container {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.action-container .layer {
		position: absolute;
		top: 0;
		left: 0;
		background: rgba(51, 51, 51, 0.5);
		width: 100%;
		height: 100%;
		z-index: 99;
	}

	.action-box {
		width: 400rpx;
		height: 240rpx;
		background: #ffffff;
		position: relative;
		z-index: 100;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.action-item {
		text-align: center;
		line-height: 120rpx;
		font-size: 34rpx;
		color: #262628;
		border-bottom: 1px solid #EFEFEF;
	}

	.unread-text {
		color: #d02129;
	}

	.tmp {
		z-index: 10000 !important;
	}
</style>
